<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        :close-on-click-modal="false"
        title="选择活动"
        width="400px"
    >
        <div class="pb10">
            <el-input
                v-model="searchKeyword"
                @keyup.enter="mdSearch"
                @clear="mdSearch"
                placeholder="输入活动名称搜索"
                clearable
            >
                <template #prepend>
                    <el-button @click="showAddActive">新增活动</el-button>
                </template>
                <template #append>
                    <el-button :icon="Search" @click="mdSearch"/>
                </template>
            </el-input>
            <div v-if="addActiveInput" class="pt10">
                <el-input
                    v-model="addKeyword"
                    @clear="clearAddKeyword"
                    show-word-limit
                    :maxlength="30"
                    placeholder="请输入新增活动名称"
                    clearable
                >
                    <template #append>
                        <el-button @click="addActive">确认添加</el-button>
                    </template>
                </el-input>
            </div>
        </div>

        <el-scrollbar v-loading="showLoading" element-loading-background="rgba(0,0,0,0)" height="300px">
            <el-radio-group v-if="showRadioList.length" v-model="radioActive">
                <el-radio v-for="row in showRadioList" :value="row.id">{{ row.name }}</el-radio>
            </el-radio-group>
            <el-empty v-else-if="!showLoading" :image-size="100"/>
        </el-scrollbar>

        <template #footer>
            <el-button @click="cancelDialog">取消</el-button>
            <el-button type="primary" :disabled="disLoading" @click="onDialog">确认</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
    import { ref, watch } from 'vue';
    import { ElMessage } from "element-plus";
    import { Search } from '@element-plus/icons-vue';
    import { getMallMajorCampaigns, postMallCampaign } from "@/assets/api";

    const props = defineProps({
        dialog: {
            type: Boolean,
            default: false,
        },
        modelValue: {
            type: [Number, String],
            default: '',
        },
        campaignType: {
            type: Number,
            default: 8
        }
    })

    const emit = defineEmits(['update:dialog', 'update:modelValue', 'change']);
    let dialogVisible = ref<boolean>(false);// 显示弹窗
    let showLoading = ref<boolean>(false);// 接口请求loading
    let disLoading = ref<boolean>(false);// 按钮禁用

    const cancelDialog = () => {
        dialogVisible.value = false;
    }
    const onDialog = () => {
        const _value: ObjValueAny = radioList.value.filter((row: ObjValueAny) => row.id === radioActive.value)[0];
        emit('update:modelValue', radioActive.value);
        emit('change', radioActive.value, _value);
        cancelDialog();
    }
    const closeDialog = () => {
        cancelDialog();
        emit('update:dialog', dialogVisible.value);
    }

    let searchKeyword = ref<string>('');// 关键字搜索
    let radioList = ref<ObjValueAny[]>([]);// 活动列表
    let showRadioList = ref<ObjValueAny[]>([]);// 显示活动列表
    let radioActive = ref<number | string>('');// 选择活动id
    const mdSearch = async () => {
        showRadioList.value = await getDataList();
    }

    const addActiveInput = ref<boolean>(false);// 显示新增活动输入框
    let addKeyword = ref<string>('');// 新增活动名称
    const showAddActive = () => {
        clearAddKeyword();
        addActiveInput.value = true;
    }
    const clearAddKeyword = () => {
        addKeyword.value = '';
    }
    const addActive = () => {
        if (!addKeyword.value.trim()) {
            ElMessage.error('活动名称不得为空');
            return;
        }
        showLoading.value = true;
        postMallCampaign({
            name: addKeyword.value,
            type: props.campaignType,
        }).then(async (resp: ObjValueAny) => {
            if (resp.code === 200) {
                ElMessage.closeAll();
                ElMessage.success('新增成功');
                initParams();
                radioList.value = await getDataList();
                showRadioList.value = radioList.value;
            } else {
                showLoading.value = false;
                ElMessage.error(`postMallCampaign：${resp.msg}`);
            }
        }).catch(() => {
            showLoading.value = false;
            ElMessage.closeAll();
        })
    }
    const getDataList = (): Promise<ObjValueAny[]> => {
        return new Promise(resolve => {
            showLoading.value = true;
            getMallMajorCampaigns({
                page: 1,
                per_page: 10000,
                keyword: searchKeyword.value,
                type: props.campaignType,
            }, { noReport: 1 }).then((resp: ObjValueAny) => {
                if (resp.code !== 200) {
                    ElMessage.error(resp.msg);
                }
                showLoading.value = false;
                resolve((resp?.data || []));
            })
        })
    }

    const initParams = () => {
        radioActive.value = '';
        searchKeyword.value = '';
        clearAddKeyword();
    }

    watch(() => props.dialog, async (newVal: boolean) => {
        dialogVisible.value = newVal;
        addActiveInput.value = false;
        initParams();
        if (newVal) {
            disLoading.value = true;
            radioActive.value = props.modelValue || '';
            radioList.value = await getDataList();
            showRadioList.value = radioList.value;
            disLoading.value = false;
        } else {
            radioList.value = [];
            showRadioList.value = [];
        }
    })

    const getModelValue = async (newVal: string | number) => {
        initParams();
        radioActive.value = newVal || '';
        radioList.value = await getDataList();
        onDialog();
    }
    defineExpose({
        getModelValue
    })
</script>

<style scoped lang="scss">
    :deep(.el-radio-group), :deep(.el-radio) {
        display: block;
    }

    :deep(.el-radio) {
        margin-right: 0;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    :deep(.el-scrollbar__wrap) {
        overflow-x: hidden;
    }

    :deep(.el-scrollbar__bar.is-horizontal) {
        height: 0;
    }
</style>